<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@include file="../base_path.jsp" %>
<html>
<head>
    <meta charset="utf-8">
    <meta name="renderer" content="webkit|ie-comp|ie-stand">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
          content="width=device-width,initial-scale=1,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no"/>
    <meta http-equiv="Cache-Control" content="no-cache"/>
    <meta http-equiv="Expires" content="0">
    <meta http-equiv="Pragma" content="no-cache">
    <meta http-equiv="description" content="">

    <link rel="stylesheet" type="text/css" href="<%=basePath%>/lib/bootstrap/3.3.7/css/bootstrap.min.css"/>
    <link rel="stylesheet" type="text/css" media="screen"
          href="<%=basePath%>/lib/jqgrid/5.2.1/css/ui.jqgrid-bootstrap.css"/>
    <link rel="stylesheet" type="text/css" media="screen" href="<%=basePath%>/lib/lobibox/css/lobibox.min.css"/>
    <link type="text/css" rel="stylesheet" href="<%=basePath%>/lib/bootstrap-select/css/bootstrap-select.min.css"/>
    <link rel="stylesheet" type="text/css" media="screen" href="<%=basePath%>/css/mycss.css"/>

    <title>业务汇总分析</title>
    <style type="text/css">
        #form_filter .control-label {
            float: left;
            padding-left: 15px;
            line-height: 30px;
            padding-top: 0px;
        }

        #form_filter .form-control {
            /* width: 60%; */
        }

        #form_filter .Wdate {
            width: 100%;
        }

        .right {
            float: right;
        }

        #chart_condition_label {
            line-height: 30px;
            text-align: right;
        }

        .dropup .dropdown-menu {
            z-index: 2000;
        }

        .first {
            opacity: 0.5;
        }

        .dpinput {
            position: relative;
            top: -3px;
            margin-right: 3px;
        }

        #chart_condition_label .btn-default {
            color: #333;
            background-color: #eff1f7;
            border-color: #eff1f7;
            border-radius: 3px;
            height: 34px;
        }

        .wbg {
        }

        .btn-file {
            float: left;
            margin-right: 12px;
        }
    </style>
</head>
<body style="min-height: 700px;">
<div class="navbar-fixed-top">
    <div class="breadcrumb">
        <span>数据报表</span>/
        <span class="active">业务汇总分析</span>
        <span class="pull-right" title="刷新">
					<div class="btn-refresh" onclick="location.replace(location.href);">
						<img src="<%=basePath%>/images/refresh.png">
					</div>
				</span>
    </div>
</div>
<div class="container-fluid">
    <div class="container-fluid-main">
        <div class="page-header">
            <h3>业务汇总分析</h3>
            <div class="header-right">
                <button type="button" class="btn btn-primary dropdown-toggle" data-toggle="dropdown"
                        aria-haspopup="true"
                        aria-expanded="false">
                    <span class="glyphicon glyphicon-download-alt"></span>
                    导出
                    <span class="caret"></span>
                </button>
                <ul class="dropdown-menu">
                    <c:choose>
                        <c:when test="${exportListSwitch == true}">
                            <li><a href="javascript:void (0);" onclick="exportExcel()">数据列表</a></li>
                        </c:when>
                        <c:otherwise></c:otherwise>
                    </c:choose>
                    <li><a href="javascript:void (0);" onclick="exportImg()">图表</a></li>
                    <!-- <li><a href="javascript:void (0);" onclick="exportAudio()">语音</a></li>
                <li><a href="javascript:void (0);" onclick="exportDialog()">导出对话文本</a></li>
                <li><a href="javascript:void (0);" onclick="exportAll()">全部</a></li> -->
                </ul>
            </div>
        </div>

        <form class="form-horizontal" id="form_filter">
            <div class="form-group form-inline">

                <label class="control-label" for="select_business_id">业务名称</label>
                <div class="col-lg-2 col-md-2 col-sm-4 col-xs-5">
                    <select class="form-control input-sm selectpicker" id="select_business_id" data-live-search="true"
                            title="请选择业务名称"
                            data-live-search-placeholder="Search" data-actions-box="true">
                        <option value="${defaultBusiness.id}" selected>${defaultBusiness.businessName}</option>
                        <c:forEach var="item" items="${businessList}">
                            <option value="${item.id}">${item.businessName}</option>
                        </c:forEach>
                    </select>
                </div>


                <label class="control-label">接听时间</label>
                <div class="col-lg-2 col-md-2 col-sm-4 col-xs-5">
                    <input type="text" class="form-control input-sm Wdate" id="begin_date" autocomplete="off"
                           disableautocomplete
                           onclick="
                                var end_date=$dp.$('end_date');
                                WdatePicker({
                                    isShowClear:false,
						            onpicked:function(dq){
                                        var myobj=isCleanEndDate(dq.cal.getNewDateStr(),end_date.value);
                                        if(!myobj.ispass){
                                            end_date.value=myobj.maxDay;
                                        }
                                        beginDateClickRefreshTaskData(dq.cal.getNewDateStr());
                                        $('#begin_time').val($('#begin_date').val());
				                        $('#end_time').val($('#end_date').val());},
						            errDealMode:1,
						            dateFmt: 'yyyy-MM-dd',
						            maxDate:'%y-%M-%d'
						            // minDate: '#F{$dp.$DV(\'%y-%M-%d\',{M:-12})}'
                                })">
                </div>
                <label class="control-label" style="padding-left: 0px;">至</label>
                <div class="col-lg-2 col-md-2 col-sm-4 col-xs-5">
                    <input type="text" class="form-control input-sm Wdate" id="end_date" autocomplete="off"
                           disableautocomplete
                           onclick="
                                var begin_date=$dp.$('begin_date');
                                var begin_datestr=begin_date.value;
                                var endDateStr='';
                                if(isEmpty(begin_datestr)){
						            bootbox.alert('请先选择开始日期');
						            return false;
                                } else {
                                    endDateStr=getMaxDay(begin_datestr);
                                }
						        WdatePicker({
						            isShowClear:false,
						            onpicked:function(dq) {
						                endDateClickRefreshTaskData(dq.cal.getNewDateStr());
						                $('#begin_time').val($('#begin_date').val());
						                $('#end_time').val($('#end_date').val());
						            },
						            errDealMode:1,
						            dateFmt: 'yyyy-MM-dd',
						            minDate:'#F{$dp.$D(\'begin_date\')}',
						            maxDate:'%y-%M-%d'
						        })">
                </div>
                <input type="button" class="btn input-sm btn-file" value="今天" onclick="setDaysBefore(0)"/>
                <input type="button" class="btn input-sm btn-file" value="近7天" onclick="setDaysBefore(6)"/>
                <input type="button" class="btn input-sm btn-file" value="近30天" onclick="setDaysBefore(29)"/>
                <button class="btn input-sm btn-file hidden" type="button" id="btn_advance_search"><span
                        class="glyphicon glyphicon-plus"
                        aria-hidden="true"></span>高級搜索
                </button>
                <input type="submit" class="btn btn-primary btn-sm" value="查询" style="float: left; margin-left: 20px"/>
            </div>


        </form>

        <!--  -->
        <div style="padding: 20px;background: #FFF;">
            <div class="panel panel-default panel-default-sample" style="margin-bottom: 0px;">
                <div class="panel-heading hide" role="tab" id="filter_box" style="background: #f6f7fa;">
                    <form class="form-inline">
                        <button class="btn btn-link btn-xs" data-toggle="collapse" data-parent="#accordion"
                                href="#collapseOne"
                                aria-expanded="true" aria-controls="collapseOne">
                            任务查询结果： 共有<strong id="strong_task_count">0</strong>个任务
                            <span class="caret"></span>
                        </button>
                        <div class="checkbox">
                            <label>
                                <input type="checkbox" id="ck_all" style="margin-left: 50px" class="dpinput"> 全选
                            </label>
                            <span style="margin-left: 20px"><em>已选择<mark id="mark_task_count">0</mark>个任务</em></span>
                        </div>

                    </form>
                </div>
                <div id="collapseOne" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingOne"
                     style="background: #f6f7fa;">
                    <div class="panel-body">
                        <div style="overflow-y:auto; overflow-x:hidden; width:100%; height:160px;">
                            <div id="ck_tasks">
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="container-fluid" style="margin-top: 0px;padding-top: 0px;padding-bottom: 0px;">
        <div class="container-fluid-main">
            <form class="form-horizontal row" id="form_filter">
                <div class="col-lg-1 col-md-2 col-sm-3 col-xs-3">
                    <select class="form-control input-sm" id="chart_type">
                        <c:forEach var="item" items="${statisticsTypeList}">
                            <option value="${item.code}">${item.name}</option>
                        </c:forEach>
                    </select>
                </div>
                <div class="col-lg-1 col-md-2 col-sm-3 col-xs-3">
                    <select class="form-control input-sm" id="real_chart_type">

                    </select>
                </div>
                <div class="col-lg-offset-7 col-md-offset-4 col-md-4 col-sm-6 col-xs-6 col-lg-3">
                    <div class="col-md-6 col-sm-6 col-xs-6" id="chart_condition_label">
                        <label>已接听量</label>
                    </div>
                    <div class="col-md-6 col-sm-6 col-xs-6">
                        <select class="form-control selectpicker" id="chart_condition" data-live-search="true">
                            <c:forEach var="item" items="${dimensionList}">
                                <optgroup label="${item.groupName}">
                                    <c:forEach var="subItem" items="${item.reportDimInfoList}">
                                        <option value="${subItem.dimKey}">${subItem.dimName}</option>
                                    </c:forEach>
                                </optgroup>
                            </c:forEach>
                        </select>
                    </div>
                </div>

            </form>
        </div>
    </div>
    <div class="container-fluid" style="margin-top: 0px;padding-top: 0px;padding-bottom: 0px;">
        <div class="container-fluid-main row" style="margin: 0;">
            <div id="container" style="width: 100%;height:300px;">

            </div>
        </div>
    </div>

    <div class="container-fluid" style="margin-top: 0px;padding-top: 0px;padding-bottom: 0px;">
        <div class="container-fluid-main">
            <table id="businessSummaryJQGrid"></table>
        </div>
    </div>
</div>
<!--_footer 作为公共模版分离出去-->
<script type="text/javascript" src="<%=basePath%>/lib/jquery/1.11.0/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="<%=basePath%>/lib/bootstrap/3.3.7/js/bootstrap.js"></script>
<script type="text/javascript" src="<%=basePath%>/lib/bootstrap-select/js/bootstrap-select.js"></script>
<script type="text/javascript" src="<%=basePath%>/lib/bootstrap-select/js/i18n/defaults-zh_CN.js"></script>
<script type="text/javascript" src="<%=basePath%>/lib/bootbox/bootbox.min.js"></script>
<script type="text/javascript" src="<%=basePath%>/lib/jqgrid/5.2.1/js/i18n/grid.locale-cn.js"></script>
<script type="text/javascript" src="<%=basePath%>/lib/jqgrid/5.2.1/js/jquery.jqGrid.min.js"></script>
<script type="text/javascript" src="<%=basePath%>/lib/My97DatePicker/4.8/WdatePicker.js"></script>
<script type="text/javascript" src="<%=basePath%>/lib/lobibox/js/lobibox.min.js"></script>
<script type="text/javascript" src="<%=basePath%>/lib/lobibox/js/messageboxes.min.js"></script>
<script type="text/javascript" src="<%=basePath%>/lib/lobibox/js/notifications.min.js"></script>
<script type="text/javascript" src="<%=basePath%>/lib/Sortable/Sortable.js"></script>
<script type="text/javascript" src="<%=basePath%>/js/common.js"></script>
<!--/_footer 作为公共模版分离出去-->

<!--请在下方写此页面业务相关的脚本-->
<script type="text/javascript" src="<%=basePath%>/js/common.js"></script>
<script type="text/javascript" src="<%=basePath%>/lib/echarts/3.7.1/echarts.js"></script>
<script type="text/javascript">
    var firstLoad = true;
    var sort; //排序对象
    var colNames = ["日期", "通话总量", "已解决量", "已解决率", "转人工量", "转人工率", "直接转人工量", "直接转人工率", "交互后转人工量", "交互后转人工率", "平均通话时长(s)", "通话总时长(s)"]
    var $Grid;
    var myChart; //图表实例对象
    var filter = false; //是否高级筛选

    var colModel = [
        {name: "call_date", index: "日期", autowidth: true, width: 60, align: "left", hidden: false, align: "left"},
        {
            name: "call_total_count",
            index: "通话总量",
            autowidth: true,
            width: 60,
            align: "left",
            hidden: false,
            align: "left"
        },
        {name: "solve_count", index: "已解决量", autowidth: true, width: 60, align: "left", hidden: false, align: "left"},
        {name: "solve_rate", index: "已解决率", autowidth: true, width: 60, align: "left", hidden: false, align: "left"},
        {
            name: "transfer_count",
            index: "转人工量",
            autowidth: true,
            width: 60,
            align: "left",
            hidden: false,
            align: "left"
        },
        {name: "transfer_rate", index: "转人工率", autowidth: true, width: 60, align: "left", hidden: false, align: "left"},
        {name: "result_direct_transfer_count", index: "直接转人工量", autowidth: true, width: 60, align: "left", hidden: false, align: "left"},
        {name: "result_direct_transfer_rate", index: "直接转人工率", autowidth: true, width: 60, align: "left", hidden: false, align: "left"},
        {name: "result_interactive_transfer_count", index: "交互后转人工量", autowidth: true, width: 60, align: "left", hidden: false, align: "left"},
        {name: "result_interactive_transfer_rate", index: "交互后转人工率", autowidth: true, width: 60, align: "left", hidden: false, align: "left"},
        {
            name: "duration_avg_talk",
            index: "平均通话时长(s)",
            autowidth: true,
            width: 60,
            align: "left",
            hidden: false,
            align: "left"
        },
        {
            name: "duration_total_talk",
            index: "通话总时长(s)",
            autowidth: true,
            width: 60,
            align: "left",
            hidden: false,
            align: "left"
        }
    ];

    <!-- console.log(colModel) -->


    getChartType(); //加载图表类型选项
    $("#real_chart_type").val("statistics_type_day");
    $("#chart_condition_label label").html($('#chart_condition option:selected').text())
    $("#chart_type").change(function () {
        getChartType();
    })

    // $("#businessSummaryJQGrid").setGridParam().hideCol("business_name");//隐藏
    initGrid()
    initTaskData();
    refreshJQGrid();

    $("#select_business_id").change(function () {
        fetchTaskInfo(getTaskFilterParamsStr());
    });
    $("#begin_date").change(function () {
        fetchTaskInfo(getTaskFilterParamsStr());
    });
    $("#end_date").change(function () {
        fetchTaskInfo(getTaskFilterParamsStr());
    });
    $("#ck_all").change(function () {
        var count = 0;
        if ($(this).prop("checked")) {
            $("#ck_tasks").find("input").each(function () {
                count++;
                $(this).prop("checked", true);
            });
            $("#mark_task_count").text(count);
        } else {
            $("#ck_tasks").find("input").each(function () {
                $(this).prop("checked", false);
            });
            $("#mark_task_count").text("0");
        }

    });


    $("#form_filter").submit(function (event) {
        //            console.log(getJQGridFilterData().tasks);
        if ($("#begin_date").val().length == 0) {
            myNotify("warning", "", "请先选择开始时间");
            return false;
        }
        if ($("#end_date").val().length == 0) {
            myNotify("warning", "", "请先选择结束时间");
            return false;
        }
        if (getJQGridFilterData().tasks == "" && filter) {
            myNotify("warning", "", "请先选择任务");
            return false;
        }

        $("#chart_type").val("group_statistics_type_time").change()
        $("#real_chart_type").val("statistics_type_day").change();
        refreshJQGrid();
        return false;
    });

    $("#ck_tasks").on("click", ".checkbox_task", function () {
        var sum = $("#strong_task_count").text();
        var checkedCount = getCheckedCount();
        $("#mark_task_count").text(getCheckedCount());
        if (sum == checkedCount) {
            $("#ck_all").prop("checked", true);
        }
        if (checkedCount < sum) {
            $("#ck_all").prop("checked", false);
        }

    });

    // 导出excel
    $("#export_excel").click(function () {
        if ($("#begin_date").val() == "") {
            myNotify("warning", "", "请先选择开始时间");
        } else if ($("#end_date").val() == "") {
            myNotify("warning", "", "请先选择结束时间");
        } else {
            var JQGridFd = JQGridFilterData();
            window.location.href = "<%=basePath%>/report/exportExcelForBusinessSummary.do?" +
                "businessId=" + JQGridFd.businessId +
                "&beginDate=" + JQGridFd.beginDate +
                "&endDate=" + JQGridFd.endDate +
                "&tasks=" + JQGridFd.tasks;
        }

    });


    //切换高级筛选
    $("#btn_advance_search").click(function () {
        filter = !filter;
        if (filter) {
            $("#filter_box").removeClass("hide");
        } else {
            $("#filter_box").addClass("hide");
        }
    })

    $(document).on("change", "#real_chart_type", function () {
        var type_code = $(this).val();
        if (type_code == "statistics_type_hour") {
            colModel[0] = {
                name: "call_hour",
                index: "时间段",
                autowidth: true,
                width: 60,
                align: "left",
                hidden: false,
                align: "left"
            },
                colNames[0] = "时间段";
        } else if (type_code == "statistics_type_day") {
            colModel[0] = {
                name: "call_date",
                index: "日期",
                autowidth: true,
                width: 60,
                align: "left",
                hidden: false,
                align: "left"
            },
                colNames[0] = "日期";
        } else if (type_code == "statistics_type_month") {
            colModel[0] = {
                name: "call_month",
                index: "月",
                autowidth: true,
                width: 60,
                align: "left",
                hidden: false,
                align: "left"
            },
                colNames[0] = "月";
        } else if (type_code == "statistics_type_year") {
            colModel[0] = {
                name: "call_year",
                index: "年",
                autowidth: true,
                width: 60,
                align: "left",
                hidden: false,
                align: "left"
            },
                colNames[0] = "月";
        } else if (type_code == "statistics_type_city") {
            colModel[0] = {
                name: "city",
                index: "城市",
                autowidth: true,
                width: 60,
                align: "left",
                hidden: false,
                align: "left"
            },
                colNames[0] = "城市";
        } else if (type_code == "statistics_type_province") {
            colModel[0] = {
                name: "province",
                index: "省",
                autowidth: true,
                width: 60,
                align: "left",
                hidden: false,
                align: "left"
            },
                colNames[0] = "省";
        }
        firstLoad = true;
        renderTableBySort();
    })

    $('#chart_condition').change(function () {
        $("#chart_condition_label label").html($('#chart_condition option:selected').text());
        initCharts();
    })

    $("#table_condition").change(function () {
        console.log($(this).val())
        var val = $(this).val()
        $(colModel).each(function (index, item) {
            var arr = ["call_hour", "call_date", "call_month", "call_year", "city", "province"]
            item.hidden = true;
            item.isDefault = 0;
            originModel[index].hidden = true;
            originModel[index].isDefault = 0;
            if (val.indexOf(item.name) > -1) {
                item.hidden = false;
                item.isDefault = 1;
                originModel[index].hidden = false;
                originModel[index].isDefault = 1;
            }
            if (arr.indexOf(item.name) > -1) {
                item.hidden = false;
                item.isDefault = 1;
                originModel[index].hidden = false;
                originModel[index].isDefault = 1;
            }

        })
        renderSortList()
        renderTableBySort();
    })


    /******************************方法声明**********************************/

    /**
     * 刷新表格数据
     */
    function refreshJQGrid() {

        $("#businessSummaryJQGrid").jqGrid("setGridParam", {
            url: "<%=basePath %>/report/getBusinessSummaryDataForJQGrid.do",
            mtype: 'POST',
            traditional: true,
            postData: getJQGridFilterData(),
            datatype: "json",
            page: 1
        }).trigger("reloadGrid");
    }
    /**
     * 构建筛选数据
     * @returns {{}}
     */
    function getJQGridFilterData() {
        var postData = {};
        postData.business_id = $("#select_business_id").find("option:selected").val() || 0;
        postData.begin_date = $("#begin_date").val();
        postData.end_date = $("#end_date").val();
        postData.tasks = getChecked();
        postData.type_code = $("#real_chart_type").val();
        return postData;
    }

    /**
     * 初始化表头数据
     */

    function initTableHead() {

    }

    function getChecked() {
        var tasks = "";
        if (filter) { //高级筛选
            $("#ck_tasks").find("input").each(function () {
                if (tasks != "" && $(this).prop("checked")) {
                    tasks += ","
                }
                if ($(this).prop("checked")) {
                    tasks += $.trim($(this).attr("value"));
                }
            });
            return tasks;
        } else { //非高级筛选
            return tasks;
        }

    }

    function getCheckedCount() {
        var count = 0;
        $("#ck_tasks").find("input").each(function () {
            if ($(this).prop("checked")) {
                count++;
            }
        });
        return count;
    }

    function fetchTaskInfo(paramsStr) {
        //        $("#ck_all").prop("checked", false);
        $.ajax({
            url: "<%=basePath%>/report/getTaskList.do",
            data: paramsStr,
            type: "post",
            async: true,
            dataType: "json",
            success: function (data) {
                if (data["errorCode"] == 0) {
                    showTaskView(data["list"])
                }
            }
        });
    }

    function initTaskData() {
        var today = getToday();
        var lastYear = getLastMonth();
        $("#begin_date").val(lastYear);
        $("#end_date").val(today);
        var paramsStr = "begin=" + lastYear + "&end=" + today + "&businessId=";
        fetchTaskInfo(paramsStr);
    }

    <!-- function getLastMonth() {} -->

    function getTaskFilterParamsStr() {
        var begin = $.trim($("#begin_date").val());
        var end = $.trim($("#end_date").val());
        var businessId = $("#select_business_id").find("option:selected").val();
        var paramsStr = "begin=" + begin + "&end=" + end + "&businessId=" + businessId;
        console.log("businessId = " + businessId)
        return paramsStr;
    }

    function beginDateClickRefreshTaskData(begin) {
        var end = $.trim($("#end_date").val());
        var businessId = $("#select_business_id").find("option:selected").val();
        var paramsStr = "begin=" + begin + "&end=" + end + "&businessId=" + businessId;
        fetchTaskInfo(paramsStr);
    }

    function endDateClickRefreshTaskData(end) {
        var begin = $.trim($("#begin_date").val());
        var businessId = $("#select_business_id").find("option:selected").val();
        var paramsStr = "begin=" + begin + "&end=" + end + "&businessId=" + businessId;
        fetchTaskInfo(paramsStr);
    }

    function showTaskView(list) {
        if (list.length > 0) {
            $("#ck_all").prop("checked", true);
            $("#ck_all").parent().parent().removeClass("disabled");
            $("#ck_all").prop("disabled", false);
        } else {
            $("#ck_all").prop("checked", false);
            $("#ck_all").parent().parent().addClass("disabled");
            $("#ck_all").prop("disabled", true);

        }

        $("#ck_tasks").empty();
        var htmlContent = "";
        var count = 0;
        for (var i = 1; i <= list.length; ++i) {
            htmlContent += "<div class='col-xs-3' style='overflow:hidden;white-space:nowrap;text-overflow:ellipsis;'><label>" +
                "<input checked type='checkbox' class='checkbox_task dpinput' value='" + list[i - 1].id + "'>" + list[i - 1].taskName +
                "</label></div>";
            if (i % 4 == 0 || i == list.length) {
                htmlContent = "<div class='row'>" + htmlContent + "</div>";
                $("#ck_tasks").append(htmlContent);
                htmlContent = "";
            }
        }
        //        console.log(htmlContent);
        //        $("#ck_tasks").html(htmlContent);
        $("#strong_task_count").text(list.length);
        $("#mark_task_count").text(list.length);
    }

    function initCharts() {
        console.log(getResult())
        var gridData = getResult();
        var chartShowType = $("#chart_condition").val();
        var type_code = $("#real_chart_type").val();
        var xAxisData = [];
        var seriesData = [];
        $(gridData).each(function (index, item) {
            seriesData.push(parseFloat(item[chartShowType]));
            if (type_code == "statistics_type_hour") {
                xAxisData.push(item.call_hour);
            } else if (type_code == "statistics_type_day") {
                xAxisData.push(item.call_date);
            } else if (type_code == "statistics_type_month") {
                xAxisData.push(item.call_month);
            } else if (type_code == "statistics_type_year") {
                xAxisData.push(item.call_year);
            } else if (type_code == "statistics_type_city") {
                xAxisData.push(item.city);
            } else if (type_code == "statistics_type_province") {
                xAxisData.push(item.province);
            }
        })
        var dom = document.getElementById("container");
        if (myChart) {
            myChart.dispose()
        }
        myChart = echarts.init(dom);
        var app = {};
        option = null;
        // app.title = '坐标轴刻度与标签对齐';

        option = {
            color: ['#3398DB'],
            tooltip: {
                trigger: 'axis',
                axisPointer: { // 坐标轴指示器，坐标轴触发有效
                    type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
                }
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true
            },
            xAxis: [{
                type: 'category',
                data: xAxisData,
                axisTick: {
                    alignWithLabel: true
                },
                show: true
            }],
            yAxis: [{
                type: 'value',
                show: true
            }],
            series: [{
                name: $('#chart_condition option:selected').text(),
                type: 'bar',
                barWidth: '60%',
                data: seriesData,
                label: {
                    normal: {
                        show: true, //显示数字
                        position: 'top', //这里可以自己选择位置
                        formatter: function (params) {
                            if (params.value > 0) {
                                return params.value;
                            } else {
                                return ' ';
                            }
                        },
                    },

                }
            }],

        };
        ;
        if (option && typeof option === "object") {
            myChart.setOption(option, true);
        }
    }

    function getChartType() { //获取图表数据
        var chart_type = $("#chart_type").val();
        $.ajax({
            url: "<%=basePath%>/report/getStatisticTypeInfo.do?type_code=" + chart_type,
            type: "post",
            async: false,
            dataType: "json",
            success: function (data) {
                var html = ''
                $(data.list).each(function (index, item) {
                    html += '<option value="' + item.code + '">' + item.name + '</option>'
                })
                $("#real_chart_type").html(html)
                $("#real_chart_type").change();
            }
        });
    }

    function getDaysBefore(days, date) {
        var date = date || new Date(),
            timestamp, newDate;
        if (!(date instanceof Date)) {
            date = new Date(date.replace(/-/g, '/'));
        }
        timestamp = date.getTime();
        newDate = new Date(timestamp - (days * 24 * 3600 * 1000));
        return [newDate.getFullYear(), newDate.getMonth() + 1, newDate.getDate()].join('-')
    }

    function setDaysBefore(days) {
        var today = getDaysBefore(0);
        var limit = getDaysBefore(days);
        $("#begin_date").val(limit);
        $("#end_date").val(today);
        fetchTaskInfo(getTaskFilterParamsStr());
    }


    function renderTableBySort() {
        if ($Grid) {
            $.jgrid.gridUnload("#businessSummaryJQGrid")
        }
        initGrid(true)
    }

    function initGrid(flag) {
        $.jgrid.defaults.responsive = true;
        $.jgrid.defaults.styleUI = "Bootstrap";
// 				var shrinkToFit = true;
// 				var showCount = 0;
// 				$(colModel).each(function(index, item) {
// 					if (!item.hidden) {
// 						showCount++
// 					}
// 				})
// 				if (showCount * 80 > $(".container-fluid").width()) {
// 					shrinkToFit = false;
// 				}
        $Grid = $("#businessSummaryJQGrid").jqGrid({
            height: 434,
            autowidth: true,
            shrinkToFit: true,
            autoScroll: false,
            /*forceFit: true, */
            colNames: colNames,
            colModel: colModel,
            viewrecords: true,
            hidegrid: false,
            multiselect: false,
            url: "<%=basePath %>/report/getBusinessSummaryDataForJQGrid.do",
            datatype: 'local',
            rownumbers: true,
            //shrinkToFit:false,
            //autoScroll: true, //开启水平滚动条
            rowNum: 1000,
            rowList: [1000],
            loadonce: true,
            footerrow: true,
            jsonReader: {
                root: "dataList",
                page: "currPage",
                total: "totalPages", //   很重要 定义了 后台分页参数的名字。
                records: "totalCount",
                repeatitems: false,
                id: "business_id"
            },
            loadComplete: function (data) {
                // 自动调整高度
                var resCount = data.records;
                var tableHeight = resCount * 30 + 40;
                $("#gbox_businessSummaryJQGrid .ui-jqgrid-bdiv").css(
                    "cssText",
                    "height: " + tableHeight + "px!important;");
            },
            gridComplete: function () {
                $("#businessSummaryJQGrid").jqGrid('setLabel', 'rn', '序号', {
                    'text-align': 'center',
                    'font-size': '12px',
                }, '');

                var ids = jQuery("#businessSummaryJQGrid").jqGrid('getDataIDs');
                var sumCallTime = 0,
                    sumCallDuration = 0;
                for (var i = 0; i < ids.length; i++) {
                    var id = ids[i];
                    var rowData = jQuery("#businessSummaryJQGrid").jqGrid('getRowData', id);
                    sumCallTime += rowData.total_count * rowData.avg_call_time;
                    sumCallDuration += rowData.answer_count * rowData.avg_duration;
                }
                console.log("sumCallTime = " + sumCallTime);
                console.log("sumCallDuration = " + sumCallDuration);
                var rowNum = parseInt($(this).getGridParam('records'), 10);
                if (rowNum > 0) {
                    $(".ui-jqgrid-sdiv").show();
                    var call_total_count = $(this).getCol('call_total_count', false, 'sum');
                    var call_answer_count = $(this).getCol('call_answer_count', false, 'sum');
                    var solve_count = $(this).getCol('solve_count', false, 'sum');
                    var transfer_count = $(this).getCol('transfer_count', false, 'sum');
                    var duration_total_talk = $(this).getCol('duration_total_talk', false, 'sum');
                    var result_direct_transfer_count = $(this).getCol('result_direct_transfer_count', false, 'sum');
                    var result_interactive_transfer_count = $(this).getCol('result_interactive_transfer_count', false, 'sum');
                    //-------------------------------------------------------

                    $(this).footerData("set", {
                        business_name: "合计",
                        call_date: '合计',
                        call_hour: '合计',
                        call_month: '合计',
                        call_year: '合计',
                        city: '合计',
                        province: '合计',
                        call_total_count: call_total_count,
                        call_answer_count: call_answer_count,

                        solve_count: solve_count,
                        solve_rate: getNumPercent(solve_count, call_total_count),
                        transfer_count: transfer_count,
                        transfer_rate: getNumPercent(transfer_count, call_total_count),
                        result_direct_transfer_count: result_direct_transfer_count,
                        result_direct_transfer_rate: getNumPercent(result_direct_transfer_count, call_total_count),
                        result_interactive_transfer_count: result_interactive_transfer_count,
                        result_interactive_transfer_rate: getNumPercent(result_interactive_transfer_count, call_total_count),
                        duration_avg_talk: keep2DecimalDigits2(duration_total_talk, call_total_count),
                        duration_total_talk: duration_total_talk
                    });

                    if (firstLoad) {
                        firstLoad = false;
                        initCharts();
                    }
                } else {
                    $(".ui-jqgrid-sdiv").hide();
                }

                if (flag) {
                    flag = false
                    setTimeout(function () {
                        refreshJQGrid()
                    }, 100)

                }
            }
        });
    }


    function getResult() { //获取结果结合的函数，可以通过此函数获取查询后匹配的所有数据行。
        var o = $("#businessSummaryJQGrid");
        var rows = o.jqGrid('getRowData'); //获取当前显示的记录
        console.log(rows)

        var rowNum = o.jqGrid('getGridParam', 'rowNum'); //获取显示配置记录数量
        var total = o.jqGrid('getGridParam', 'records'); //获取查询得到的总记录数量
        o.jqGrid('setGridParam', {
            rowNum: total
        }).trigger('reloadGrid'); //设置rowNum为总记录数量并且刷新jqGrid，使所有记录现出来调用getRowData方法才能获取到所有数据
        var rows = o.jqGrid('getRowData'); //输出所有匹配的

        o.jqGrid('setGridParam', {
            rowNum: rowNum
        }).trigger('reloadGrid'); //还原原来显示的记录数量
        return rows;
    }

    //导出图片
    function exportImg() {
        var canvas = $("#container").find("canvas")[0]
        var context = canvas.getContext("2d");
        var imageData = context.getImageData(0, 0, canvas.width, canvas.height);
        for (var i = 0; i < imageData.data.length; i += 4) {
            // 当该像素是透明的,则设置成白色
            if (imageData.data[i + 3] == 0) {
                imageData.data[i] = 255;
                imageData.data[i + 1] = 255;
                imageData.data[i + 2] = 255;
                imageData.data[i + 3] = 255;
            }
        }

        context.putImageData(imageData, 0, 0);
        var image = new Image();

        image.src = myChart.getDataURL({
            type: "png",
            pixelRatio: 2, //放大2倍
            backgroundColor: '#fff'
        });

        var a = document.createElement("a");
        a.style = "display: none";
        a.href = image.src;

        //设置图片名称
        var bName = $("#select_business_id").find("option:selected").text();
        var cName = $("#chart_condition").find("option:selected").text();
        var tName = $("#real_chart_type").find("option:selected").text();
        var time = getDownTime();
        a.download = bName + '_' + cName + '_' + tName + '_' + time;
        requestAnimationFrame(function () {
            a.click();
        });

        var ratio = getPixelRatio(context); // 关键代码
        console.log(ratio)


    }

    function getDownTime() {
        var myDate = new Date();

        return myDate.getFullYear() + '_' + (myDate.getMonth() + 1) + '_' + myDate.getDate() + '_' + myDate.getHours() +
            '_' + myDate.getMinutes() + '_' + myDate.getSeconds()
    }

    function exportExcel() {
        var selectOption = []
        $(colModel).each(function (index, item) {
            if (!item.hidden) {
                selectOption.push(item.name);
            }
        })
        var postData = getJQGridFilterData();
        titles = selectOption.join(",");
        postData.titles = titles;
        console.log(postData)
        var paramArr = []
        var paramStr = ''
        for (var i in postData) {
            console.log(i)
            paramArr.push(i + '=' + postData[i])
        }

        paramStr = paramArr.join("&");
        window.location.href = "<%=basePath%>/report/exportExcelForBusinessSummary.do?" + paramStr
    }

    function getPixelRatio(context) {
        var backingStore = context.backingStorePixelRatio ||
            context.webkitBackingStorePixelRatio ||
            context.mozBackingStorePixelRatio ||
            context.msBackingStorePixelRatio ||
            context.oBackingStorePixelRatio ||
            context.backingStorePixelRatio || 1;
        return (window.devicePixelRatio || 1) / backingStore;
    };
</script>
</body>
</html>
